function   smolayak_solve_parameter_combinations( parameters_matrix,  par_baseline,   p_baseline,  solution_path,  solve_model_again)
% Usage: solve_parameter_combinations( parameters_matrix,  par_baseline,   p_baseline,  path)
%
% solve all the parameter combinations stored in "parameters_matrix", and
% then output the solution files to path. 

N_trials = size(parameters_matrix, 1); 
p_2D_init = p_baseline;
% save files
parsave = @(filename, model_sol)  save(filename, 'model_sol');
% initial parameters for the credit spread definitions

if( nargin<4 )
    solve_model_again = false;
end

% Solve all the scenarios
N_batch = 60;
for( start_index = 1:N_batch:N_trials )
    parfor( iter = start_index: min((start_index+N_batch-1), N_trials) )  
        file_path = [solution_path, num2str(iter), '.mat'];
        try
            par = smolayak_generate_par_with_vector( parameters_matrix(iter,:),  par_baseline  );   % note: a new parameter struct is generated so that par_baseline is not changed during the process. 
            if( solve_model_again  ||   (~solve_model_again)&&(~isfile(file_path))  )    % If we want to solve the model again regardless, or we don't want to solve the model again but the model does not exist yet
                disp( [ '---------------solving for ', file_path, '-------------------' ] )
                % First solve the model
                mkdir(solution_path);    % If there is no directory of "solution_path", then create one.
                model_sol = find_solution( p_2D_init,  par  );    
                parsave( file_path, model_sol );   % save this baseline version
            end
        catch exception
           disp( ['!!!! Error in finding a solution !!!! At iteration ', num2str(iter)] );
        end
    end
end

